package com.test.QtestServer.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.test.QtestServer.pojo.Result;
import com.test.QtestServer.pojo.User;
import com.test.QtestServer.service.TokenService;
import com.test.QtestServer.service.UserService;
import com.test.QtestServer.utils.JwtUtil;
import com.test.QtestServer.utils.Md5Util;

@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/register")
    public Result register(String username,String password){
        User u = userService.findByUserName(username);
        if (u == null){
            userService.register(username, password);
            return Result.success();
        }else{
            return Result.error("该用户名已经被注册");
        }
    }


    @PostMapping("/login")
    public Result login(String username,String password) {
        User u = userService.findByUserName(username);
        //判断用户是否存在
        if(u == null){
            return Result.error("用户不存在");
        }
        //判断密码是否正确
        if(Md5Util.getMD5String(password).equals(u.getPassword())){
             //登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("username",u.getUsername());
            String token = JwtUtil.genToken(claims);
            //偷懒不放redis了，直接在mysql搞个表
            tokenService.addToken(u.getId(),token);
            return Result.success(token);
        }else{
            return Result.error("密码错误");
        }
    }


}
